import * as XLSX from "xlsx"
import {ElMessage} from "element-plus";

/**
 * 导出
 */
const XLSXExport = (tableData: any[], tableEls?: any[]) => {
    if (!tableEls) {
        ElMessage.warning("无表格结构，请检查")
        return
    }

    if (!tableData) {
        ElMessage.warning("无表格数据，请检查")
        return
    }

    const propToLabel: any = {};

    tableEls.forEach((item: any) => {
        propToLabel[item.prop] = item.label;
    })

    // 处理第一个数组中的每个对象
    const result = tableData.map((obj: any) => {
        const newObj: any = {};
        for (const prop in propToLabel) {
            if (obj.hasOwnProperty(prop)) {
                newObj[propToLabel[prop]] = obj[prop];
            }
        }
        return newObj;
    });

    // 将JSON数据转换为工作表
    const worksheet = XLSX.utils.json_to_sheet(result)

    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1')

    XLSX.writeFile(workbook, '导出数据.xlsx')
}

export {
    XLSXExport
}